package com.cloudinnov.utils;

import java.awt.Color;
import java.awt.Font;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import com.cloudinnov.utils.model.BxClientModel;

import onbon.bx05.Bx5GEnv;
import onbon.bx05.Bx5GException;
import onbon.bx05.Bx5GScreen;
import onbon.bx05.Bx5GScreenClient;
import onbon.bx05.Bx5GScreenProfile;
import onbon.bx05.area.TextCaptionBxArea;
import onbon.bx05.area.page.TextBxPage;
import onbon.bx05.file.BxFileWriterListener;
import onbon.bx05.file.ControllerConfigBxFile;
import onbon.bx05.file.ProgramBxFile;
import onbon.bx05.message.common.ErrorType;
import onbon.bx05.message.led.ReturnControllerStatus;
import onbon.bx05.utils.DisplayStyleFactory;
import onbon.bx05.utils.DisplayStyleFactory.DisplayStyle;
import onbon.bx05.utils.TextBinary;

/**
 * 情报板工具类
 * @ClassName: BxClientUtil
 * @Description: TODO
 * @author: ningmeng
 * @date: 2016年11月25日 下午4:25:11
 */
public class BxClientUtil implements BxFileWriterListener<Bx5GScreen> {
	public static final int STATUS_NOT_FOUND_CODE = 404;
	public static final String STATUS_NOT_FOUND_MSG = "未找到该设备";

	public static Bx5GScreenClient initialization(String ip, int port, String alias) throws Exception {
		// SDK 初始化
		// Bx5GEnv.initial("log.properties");
		Bx5GEnv.initial("log.properties", 5000);
		// 创建 screen 对象，用于对控制器进行访问
		Bx5GScreenClient screen = new Bx5GScreenClient(alias);
		//
		// 连接控制器
		// 其中, 192.168.88.199 为控制器的实际 IP，请根据实际情况填写。
		// 如你不知道控制器的 IP 是多少，请先使用 LEDSHOW TW 软件对控制器进行 IP 设置
		// 端口号默认为 5005
		if (!screen.connect(ip, port)) {
			// 未找到该设备
			screen = null;
		}
		return screen;
	}
	/**
	 * 显示屏参数只需要在显示屏第一次安装时使用一次即可。没有必要每次发送节目前都设置一次。
	 * @Title: initScreenConfig
	 * @Description: TODO
	 * @param ip
	 * @param port
	 * @param alias
	 * @param controllerName
	 * @param width 显示屏的宽度（单位：像素)
	 * @param height 显示屏的高度（单位：像素）
	 * @param manualBrightness 将屏幕亮度调整至 X 1-16
	 * @return
	 * @throws Exception
	 * @return: int
	 */
	public static int initScreenConfig(String ip, int port, String alias, String controllerName, int width, int height,
			int manualBrightness) throws Exception {
		int statusCode = 0;
		Bx5GScreenClient screen = initialization(ip, port, alias);
		// 以下为显示屏参数的设置方法
		// ！！！注意：显示屏参数只需要在显示屏第一次安装时使用一次即可。没有必要每次发送节目前都设置一次。
		ControllerConfigBxFile bxFile = new ControllerConfigBxFile();
		bxFile.setControllerName(controllerName);
		// bxFile.setAddress(new byte[] { (byte) 0xb0, 0x05 });
		// 显示屏的宽度（单位：像素）
		bxFile.setScreenWidth(width);
		// 显示屏的高度（单位：像素）
		bxFile.setScreenHeight(height);
		// 将参数文件写入控制器
		screen.writeConfig(bxFile);
		// 通常参数配置完后，控制器会进行重启，需等待一段时间再对控制器进行操作
		Thread.sleep(5000);
		// 校时
		screen.syncTime();
		// 调整亮度
		screen.manualBrightness((byte) manualBrightness); // 将屏幕亮度调整至 X
		// 可以通过 screen 的 getProfile 方法获取控制器参数
		// 也可通过此方法验证控制器参数是否被正确设置
		Bx5GScreenProfile profile = screen.getProfile();
		org.apache.log4j.Logger.getLogger(BxClientUtil.class).info("screen width : " + profile.getWidth());
		org.apache.log4j.Logger.getLogger(BxClientUtil.class).info("screen height : " + profile.getHeight());
		//
		// 继开与控制器之间的链接
		screen.disconnect();
		return statusCode;
	}
	/**
	 * 关机
	 * @Title: turnOff
	 * @Description: TODO
	 * @param ip
	 * @param port
	 * @param alias
	 * @return
	 * @throws Exception
	 * @return: int
	 */
	public static int turnOff(String ip, int port, String alias) throws Exception {
		Bx5GScreenClient screen = initialization(ip, port, alias);
		if (screen.turnOff().isOK()) {
			return 1;
		} else {
			return 0;
		}
	}
	/**
	 * 开机
	 * @Title: turnOn
	 * @Description: TODO
	 * @param ip
	 * @param port
	 * @param alias
	 * @return
	 * @throws Exception
	 * @return: int
	 */
	public static int turnOn(String ip, int port, String alias) throws Exception {
		Bx5GScreenClient screen = initialization(ip, port, alias);
		if (screen.turnOn().isOK()) {
			return 1;
		} else {
			return 0;
		}
	}
	
	public static boolean deleteProgram(String ip, int port, String alias, String programName) throws Exception {
		Bx5GScreenClient screen = initialization(ip, port, alias);
		if (screen == null) {
			System.out.println("初始化失败,请检查网络连接");
			System.out.println();
			return false;
		}else{
			return screen.deleteProgram(programName).isOK();
		}
	}
	
	public static boolean deletePrograms(String ip, int port, String alias) {
		Bx5GScreenClient screen;
		try {
			screen = initialization(ip, port, alias);
			if (screen == null) {
				System.out.println("初始化失败,请检查网络连接");
				System.out.println();
				return false;
			}else{
				return screen.deletePrograms().isOK();
			}
		} catch (Exception e) {
			System.out.println("初始化失败,请检查网络连接"+e);
			return false;
		}
	}
	
	public static List<String> selectPrograms(BxClientModel model) throws Exception {
		Bx5GScreenClient screen = initialization(model.getIp(), model.getPort(), model.getAlias());
		if (screen == null) {
			System.out.println("初始化失败,请检查网络连接");
			System.out.println();
			return Collections.emptyList();
		}else{
			return screen.readProgramList();
		}
	}
	/**
	 * 设置显示屏单个文本内容
	 * @Title: setScreenText
	 * @Description: TODO
	 * @param ip
	 * @param port
	 * @param alias
	 * @param programName 程序名称
	 * @return
	 * @throws Exception
	 * @return: int
	 */
	public static BxClientModel setScreenText(BxClientModel model) throws Exception {
		Bx5GScreenClient screen = initialization(model.getIp(), model.getPort(), model.getAlias());
		if (screen == null || !screen.isConnected()) {
			System.out.println("初始化失败,请检查网络连接");
			System.out.println();
			return model;
		}
		Bx5GScreen.Result<ReturnControllerStatus> result1 = screen.checkControllerStatus();
		if (result1.isOK()) {
			ReturnControllerStatus stauts = result1.reply;
			stauts.getBrightness();
			stauts.getRtcDay();
			stauts.getScreenOnOff();
			model.setOK(result1.isOK());
		} else {
			ErrorType error = result1.getError();
			model.setError(error);
			return model;
		}
		DisplayStyle[] styles = DisplayStyleFactory.getStyles().toArray(new DisplayStyle[0]);
		TextCaptionBxArea area = new TextCaptionBxArea(model.getX(), model.getY(), screen.getProfile().getWidth(),
				screen.getProfile().getHeight(), screen.getProfile());
		ProgramBxFile program = new ProgramBxFile(model.getProgramName(), screen.getProfile());
		TextBxPage page = new TextBxPage(new Font(model.getFontName(), Font.PLAIN, screen.getProfile().getHeight()));
		page.setForeground(new Color(Integer.parseInt(model.getFontColor().replace("#", ""), 16)));
		page.setText(model.getText());
		page.setStayTime(0);
	    page.setSpeed(5);
		// 设置文本水平对齐方式
		page.setHorizontalAlignment(TextBinary.Alignment.NEAR);
		// 设置文本垂直居中方式
		page.setVerticalAlignment(TextBinary.Alignment.NEAR);
		page.setLineBreak(true);
		page.setDisplayStyle(styles[model.getStyleIndex()]);
		page.setHeadTailInterval(20);//设定首尾相连间隔
		area.addPage(page);
		
		program.addArea(area);
		screen.deletePrograms();
		screen.writeProgram(program);
		screen.disconnect();
		return model;
	}
	/**
	 * 设置显示屏多个文本内容
	 * @Title: setScreenText
	 * @Description: TODO
	 * @param ip
	 * @param port
	 * @param alias
	 * @param programName 程序名称
	 * @return
	 * @throws Exception
	 * @return: int
	 */
	public static BxClientModel setScreenTexts(BxClientModel model) throws Exception {
		Bx5GScreenClient screen = initialization(model.getIp(), model.getPort(), model.getAlias());

		if (screen == null || !screen.isConnected()) {
			System.out.println("初始化失败,请检查网络连接");
			System.out.println();
			return model;
		}
		Bx5GScreen.Result<ReturnControllerStatus> result1 = screen.checkControllerStatus();
		if (result1.isOK()) {
			ReturnControllerStatus stauts = result1.reply;
			stauts.getBrightness();
			stauts.getRtcDay();
			stauts.getScreenOnOff();
			model.setOK(result1.isOK());
		} else {
			ErrorType error = result1.getError();
			model.setError(error);
			return model;
		}
		// 特效
		DisplayStyle[] styles = DisplayStyleFactory.getStyles().toArray(new DisplayStyle[0]);
		TextCaptionBxArea area = new TextCaptionBxArea(model.getX(), model.getY(), screen.getProfile().getWidth(),
				screen.getProfile().getHeight(), screen.getProfile());
		ProgramBxFile program = new ProgramBxFile(model.getProgramName(), screen.getProfile());
		//TextBxPage page = new TextBxPage(new Font(model.getFontName(), Font.PLAIN, model.getFontSize()));
		TextBxPage page = new TextBxPage(new Font(model.getFontName(), Font.PLAIN, screen.getProfile().getHeight()));
		page.setText(model.getText());
		// 设置文本颜色
        page.setForeground(new Color(Integer.parseInt(model.getFontColor().replace("#", ""), 16)));
        page.setStayTime(0);
        page.setSpeed(5);
        // 设置文本水平对齐方式
        page.setHorizontalAlignment(TextBinary.Alignment.NEAR);
        // 设置文本垂直居中方式
        page.setVerticalAlignment(TextBinary.Alignment.NEAR);
        area.addPage(page);
		// 调整特技方式
		page.setDisplayStyle(styles[model.getStyleIndex()]);
		page.setHeadTailInterval(20);//设定首尾相连间隔
		area.addPage(page);
		if (model.getStartTime() > 0 && model.getEndTime() > 0) {
			Calendar startTime = Calendar.getInstance();
			startTime.setTimeInMillis(model.getStartTime());
			Calendar endTime = Calendar.getInstance();
			endTime.setTimeInMillis(model.getEndTime());
			
			program.setEndYear(endTime.get(Calendar.YEAR));
			program.setEndMonth(endTime.get(Calendar.MONTH) + 1);
			program.setEndDay(endTime.get(Calendar.DAY_OF_MONTH));
			// 开始和结束时间
			program.addPlayPeriodSetting(startTime.get(Calendar.HOUR_OF_DAY), startTime.get(Calendar.MINUTE), startTime.get(Calendar.SECOND) +1,
					endTime.get(Calendar.HOUR_OF_DAY), endTime.get(Calendar.MINUTE), endTime.get(Calendar.SECOND));
		}
		program.addArea(area);
		screen.writeProgram(program);
		screen.disconnect();
		return model;
	}
	
	
	public static void main(String[] args) throws Exception {
		// initScreenConfig("192.168.199.125", 5005, "test", "controller", 160, 32, 16);
		// setScreenText("192.168.199.125", 5005, "test", "P111", "2016年11月29日,天气:雨夹雪,微风,空气质量:94 良",
		// 0, 0);
		/*BxClientModel bxModel = new BxClientModel();
		bxModel.setIp("192.168.199.125");
		bxModel.setPort(5005);
		//bxModel.setAlias("演示模板");
		bxModel.setProgramName("P000");
		bxModel.setText("雨天路滑,请减速慢行");
		bxModel.setStyleIndex(4);
		bxModel.setStartTime(System.currentTimeMillis()+5000);
		bxModel.setEndTime(System.currentTimeMillis()+20000); 
		BxClientUtil.setScreenTexts(bxModel);
		
		bxModel = new BxClientModel();
		bxModel.setIp("192.168.199.125");
		bxModel.setPort(5005);
		//bxModel.setAlias("演示模板");
		bxModel.setProgramName("P001");
		bxModel.setText("111111111111！");
		bxModel.setStyleIndex(4);
		bxModel.setStartTime(System.currentTimeMillis()+25000);
		bxModel.setEndTime(System.currentTimeMillis()+40000); 
		BxClientUtil.setScreenTexts(bxModel);*/
		
		System.out.println(new Color(Integer.parseInt("ff0000", 16)));

	}
	
	/**
	 * 设置显示屏单个文本内容
	 * @Title: setScreenText
	 * @Description: TODO
	 * @param ip
	 * @param port
	 * @param alias
	 * @param programName 程序名称
	 * @return
	 * @throws Exception
	 * @return: int
	 */
	public static BxClientModel selectInfoBoardStatus(BxClientModel model) throws Exception {
		Bx5GScreenClient screen = initialization(model.getIp(), model.getPort(), model.getAlias());
		if (screen == null || !screen.isConnected()) {
			System.out.println("初始化失败,请检查网络连接");
			return model;
		}
		Bx5GScreen.Result<ReturnControllerStatus> result1 = screen.checkControllerStatus();
		if (result1.isOK()) {
			ReturnControllerStatus stauts = result1.reply;
			stauts.getBrightness();
			stauts.getRtcDay();
			stauts.getScreenOnOff();
			model.setOK(result1.isOK());
		} else {
			ErrorType error = result1.getError();
			model.setError(error);
		}
		return model;
	}
	
	@Override
	public void fileWriting(Bx5GScreen bx6GScreen, String s, int i) {
	}
	@Override
	public void fileFinish(Bx5GScreen bx6GScreen, String s, int i) {
	}
	@Override
	public void progressChanged(Bx5GScreen bx6GScreen, String s, int i, int i1) {
	}
	@Override
	public void cancel(Bx5GScreen bx6GScreen, String s, Bx5GException e) {
	}
	@Override
	public void done(Bx5GScreen bx6GScreen) {
	}
}
